import axios from 'axios';
import store from './store';
import { USER_KEY, LOGIN_URL,HTTP_STATUS_MESSAGE } from './const';
import { notification, Modal } from 'antd';
import router from 'umi/router';

/*
 *@Description: 请求通用方法封装
 *@ClassAuthor: beautifulHao
 *@Date: 2019-07-12 14:47:25
 */
class HttpRequest {
  constructor() {
    // loading 加载多请求等待
    this.queue = {};
  }
  getInsideConfig() {
    const config = {
      headers: {},
      timeout: 1000 * 60,
    };
    return config;
  }

  /*
   * 前端请求拦截
   *@params: axios实例
   *@returns: promise
   */
  interceptors(instance) {
    instance.interceptors.request.use(
      config => {
        //后期jwt认证是采用
        const userInfo = store.get(USER_KEY);

        if (userInfo && userInfo.accessToken && userInfo.accessToken.length > 0) {
          config.headers['Authorization'] = 'Bearer ' + userInfo.accessToken;
        }

        return config;
      },
      error => {
        return Promise.reject(error);
      },
    );

    instance.interceptors.response.use(
      res => {
        return res.data;
      },
      error => {
        if (error.response) {
          if (error.response.status === 401) {
            Modal.confirm({
              title: '提示',
              content: `当前请求需要身份认证或者登录身份失效,是否跳转到登录界面？`,
              okText: '确认',
              cancelText: '取消',
              onOk: () => {
                router.push({
                  pathname: LOGIN_URL,
                });
              },
            });
          }
          else {
            let msg = error.message || HTTP_STATUS_MESSAGE[error.response.status]
            notification.error({
              message: `提交或请求数据失败：${msg}`,
            });
          }
        }

        return Promise.reject(error);
      },
    );
  }
  request(options) {
    const instance = axios.create();
    options = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance);
    return instance(options);
  }
}

export default HttpRequest;
